/**
 * Created by Ding on 2016/4/8.
 * Copyright (c) 2016, auais.com All Rights Reserved.
 * File Name:
 * Package Name:
 * Date:2016/4/8 11:23
 */
const ObjectID = require('mongodb').ObjectID;
const mongo = require('mongodb');
const GridStore = require('mongodb').GridStore;
const fs = require("fs");
const path = require('path');
const Grid = require('gridfs-stream');
const Busboy = require('busboy');
const inspect = require('util').inspect;
const gm = require("gm");
module.exports = {
    handler: (req, res, next)=> {

        const compress = req.query.compress;
        const gfs = Grid(req.mongo, mongo);
        var doc = req.body;
        var base64data = doc.base64data;
        //替换空格为+号，防止有些时候数据发生转码
        base64data = base64data.replace(/\s/g, "+");
        //删除base64的头信息，如果有
        base64data = base64data.replace(/^data:\S+base64,/, "");
        //console.log(base64data);

        //todo:将buffer直接转转成stream，解决中间生成文件的过程
        var filesize = 0;
        var id = new ObjectID();
        var buffer = new Buffer(base64data, "base64");
        var newfilename = id + ".jpg";
        newfilename = path.join(__dirname, newfilename);
        fs.writeFileSync(newfilename, buffer);
        var readstream = fs.createReadStream(newfilename);
        var writestream = gfs.createWriteStream({
            _id: id,
            mode: "w",
            filename: doc.title || id.toString(),
            content_type: doc.content_type || "image/jpeg"
        });

        readstream.pipe(writestream);

        readstream.on('end', function () {
            console.log("end");
            var url = "http://" + req.headers.host + "/res/" + id+"/content";
            var fileObj = {
                id: id,
                url: url,
                "size": filesize,
                "state": "SUCCESS"
            };
            res.json(fileObj);

            var fn = function (err) {
                console.log(err)
            };
            fs.unlink(newfilename, fn);

        });
    }
};